import java.io.*;
import java.util.*;

/**
 * <p>Title: OWI</p>
 *
 * <p>Description: </p>
 *
 * <p>Copyright: Copyright (c) 2005</p>
 *
 * <p>Company: </p>
 *
 * @author David So
 * @version 1.0
 */
public class NMEAReader
    extends Thread {

  InputStream rawIn = null;

  String gpsUTC = "";
  String gpsQual = "";
  String gpsLat = "";
  String gpsLon = "";
  String gpsLatDisp = "";
  String gpsLonDisp = "";
  String gpsSpeed = "";
  String gpsDate = "";
  String HDOP = "";
  String alt = "";

  Coord coord;

  public NMEAReader(InputStream is) {
    rawIn = is;
  }

  public void run() {

    String nmeaSentence = new String();
    int loopCounter = 0;

    while (true) {

      loopCounter++;

      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      int ch = 0;
      //each NMEA Message ends with <CR><LF>
      //System.out.println("inStream_before_readln:" + rawIn.available());

      try {
        while ( (ch = rawIn.read()) != '\n') {
          baos.write(ch);
        }
        baos.flush();
      }
      catch (Exception e) {
        System.out.println("Couldn't write/flush ByteArrayOutputStream" + e);
      }
      nmeaSentence = baos.toString();
   //   System.out.println("nmeaSentence = " + nmeaSentence);

      try {
        baos.close();
      }
      catch (IOException ex) {
        System.out.println("Couldn't close ByteArrayOutputStream" + ex);
      }

      NMEA nmea = new NMEA(nmeaSentence); // remove *hh checksum
      if (loopCounter % 4 == 0) {
        try {
          sleep(1000);

          SandBox sb = new SandBox();
          System.out.println(NMEA.lat + " " + sb.formatLat(NMEA.lat));
          System.out.println(sb.formatLon(NMEA.lon));
        }
        catch (Exception ex) {
          ex.printStackTrace();
          System.out.println("Cant sleep NMEA thread");

        }
      }
    }
  }
}
